using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.Logging;
using WpfClient.Core.Interfaces;
using WpfClient.Core.Models;

namespace WpfClient.Application.ViewModels
{
    /// <summary>
    /// 主窗口ViewModel，使用CommunityToolkit.Mvvm源生成器
    /// </summary>
    public partial class MainViewModel : BaseViewModel
    {
        private readonly IUserService _userService;
        private readonly ILogger<MainViewModel> _logger;

        [ObservableProperty]
        private string _title = "WpfClient 应用程序";

        [ObservableProperty]
        private string _statusMessage = "就绪";

        [ObservableProperty]
        private ObservableCollection<User> _users = new();

        [ObservableProperty]
        private int _totalUsers;

        [ObservableProperty]
        private int _activeUsers;

        [ObservableProperty]
        private bool _isLoadingUsers;

        public MainViewModel(IUserService userService, ILogger<MainViewModel> logger)
        {
            _userService = userService;
            _logger = logger;
            
            _logger.LogInformation("MainViewModel 已初始化");
            
            // 初始化时加载用户数据
            _ = LoadUsersAsync();
        }

        [RelayCommand]
        private void ShowMessage()
        {
            var message = $"按钮被点击了！时间：{DateTime.Now:HH:mm:ss}";
            StatusMessage = message;
            _logger.LogInformation("用户点击了显示消息按钮: {Message}", message);
        }

        [RelayCommand]
        private void OpenUserManagement()
        {
            try
            {
                _logger.LogInformation("用户请求打开用户管理窗口");
                
                // 使用消息传递来通知UI层打开窗口
                WeakReferenceMessenger.Default.Send(new OpenWindowMessage("UserManagement"));
                StatusMessage = "正在打开用户管理窗口...";
                
                _logger.LogInformation("用户管理窗口打开请求已发送");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "打开用户管理窗口时发生错误");
                StatusMessage = $"打开用户管理窗口失败: {ex.Message}";
            }
        }

        [RelayCommand]
        private async Task LoadUsersAsync()
        {
            try
            {
                _logger.LogInformation("开始加载用户数据");
                IsLoadingUsers = true;
                StatusMessage = "正在加载用户数据...";

                var users = await _userService.GetAllUsersAsync();
                
                Users.Clear();
                foreach (var user in users)
                {
                    Users.Add(user);
                }

                TotalUsers = Users.Count;
                ActiveUsers = Users.Count(u => u.IsActive);

                var message = $"已加载 {TotalUsers} 个用户，其中 {ActiveUsers} 个活跃用户";
                StatusMessage = message;
                
                _logger.LogInformation("用户数据加载完成: 总数={TotalUsers}, 活跃={ActiveUsers}", TotalUsers, ActiveUsers);
            }
            catch (Exception ex)
            {
                var errorMessage = $"加载用户数据失败: {ex.Message}";
                StatusMessage = errorMessage;
                _logger.LogError(ex, "加载用户数据时发生错误");
            }
            finally
            {
                IsLoadingUsers = false;
            }
        }

        [RelayCommand]
        private void Exit()
        {
            _logger.LogInformation("用户请求退出应用程序");
            System.Windows.Application.Current.Shutdown();
        }
    }

    /// <summary>
    /// 打开窗口消息
    /// </summary>
    public record OpenWindowMessage(string WindowName);
}